package com.dangwen.proto.test;
import java.io.*;

public class ObjectConverter {
    // 将对象转换为字节数组
    public static byte[] objectToBytes(Object obj) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutput out = null;
        byte[] bytes;
        try {
            out = new ObjectOutputStream(bos);
            out.writeObject(obj);
            bytes = bos.toByteArray();
        } finally {
            if (out != null) {
                out.close();
            }
            bos.close();
        }
        return bytes;
    }

    // 将字节数组转换为对象
    public static Object bytesToObject(byte[] bytes) throws IOException, ClassNotFoundException {
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        ObjectInput in = null;
        Object obj;
        try {
            in = new ObjectInputStream(bis);
            obj = in.readObject();
        } finally {
            bis.close();
            if (in != null) {
                in.close();
            }
        }
        return obj;
    }
}

